from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError

from web.models import UserInfo


# 利用django的form组件来完成注册界面（register.html）
class UserForm(forms.Form):
    user = forms.CharField(
        max_length=32, error_messages={"required": "用户名必须填写！"}, label="用户名",
        widget=widgets.TextInput(
            attrs={"class": "form-control"}
        ))
    pwd = forms.CharField(
        max_length=32, error_messages={"required": "密码必须填写！"}, label="密码",
        widget=widgets.PasswordInput(
            attrs={"class": "form-control"}
        ))
    re_pwd = forms.CharField(
        max_length=32, error_messages={"required": "必须再次输入密码！"}, label="确认密码",
        widget=widgets.PasswordInput(
            attrs={"class": "form-control"}
        ))
    email = forms.EmailField(
        max_length=32, error_messages={"required": "邮箱必须填写！"}, label="邮箱",
        widget=widgets.EmailInput(
            attrs={"class": "form-control"}
        ))

    # 检测数据库中是否已有该用户名
    def clean_user(self):
        value = self.cleaned_data.get("user")
        user = UserInfo.objects.filter(username=value).first()

        if not user:
            return value
        else:
            raise ValidationError("该用户已注册")

    # 密码不一致的全局钩子
    def clean(self):
        pwd = self.cleaned_data.get("pwd")
        re_pwd = self.cleaned_data.get("re_pwd")

        if pwd and re_pwd:
            if pwd == re_pwd:
                return self.cleaned_data
            else:
                raise ValidationError("两次密码不一致!")
        else:
            return self.cleaned_data
